package com.yc.springmvc.controller;

import com.yc.springmvc.bean.Person;
import com.yc.springmvc.bean.Result;
import com.yc.springmvc.biz.BizException;
import com.yc.springmvc.biz.UserBiz;
import org.springframework.http.MediaType;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UserDo {

    @RequestMapping(path = "reg1")
    public Result reg1(Person p,
                      Errors errors){   // 验证结果
        if(errors.hasErrors()){
            return new Result(0, "字段验证错误", errors.getAllErrors());
        }
        // TODO 业务 和 DAO 自行实现
        return new Result(1, "注册成功!", p);
    }

    @RequestMapping("reg")
    public Result reg(@RequestBody @Valid Person p,
                      Errors errors){   // 验证结果
        if(errors.hasErrors()){
            return new Result(0, "字段验证错误", errors.getAllErrors());
        }
        // TODO 业务 和 DAO 自行实现
        return new Result(1, "注册成功!", p);
    }

    @PostMapping("uploadfile")
    public Result upload( @RequestParam("file") MultipartFile file)
            throws IOException {
        String filename = file.getOriginalFilename();
        String newFilename = UUID.randomUUID().toString()+"."
                // 後綴
                +filename.substring(filename.lastIndexOf(".")+1);
        File fileObj = new File("F:\\上课视频\\135\\0402",newFilename);
        file.transferTo(fileObj);
        // F:\上课视频\135\0402\a.jpg => 映射為 /upload/a.jpg
        return new Result(1,"文件上傳成功!", "upload/" + newFilename);
    }

    @Resource
    UserBiz biz;

    @PostMapping("login")
    Result login (@Valid Person person, Errors errors,
                  HttpSession session) throws BizException {
        if(errors.hasFieldErrors("name") ||
                errors.hasFieldErrors("pwd")){
            return new Result(0,"字段验证错误", errors.getAllErrors());
        }
//        try {
//            Person loginedUser = biz.login(person);
//        } catch (BizException e) {
//            return new Result(0,e.getMessage(), null);
//        }
        Person loginedUser = biz.login(person);
        session.setAttribute("loginedUser", loginedUser);
        return new Result(1,"登录成功!", person);
    }

    // 異常攔截方法 => 只在当前类有效
//    @ExceptionHandler
//    public Result handleBizException(BizException e){
//        return new Result(0,e.getMessage(), null);
//    }

    @GetMapping("logout")
    ModelAndView logout(HttpSession session, ModelAndView mav){
        session.invalidate();
        mav.setViewName("redirect:index.html");
        return mav;
    }

}
